#! /bin/bash

#  This script is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License version 2 as
#  published by the Free Software Foundation.
#
#  See the COPYING and AUTHORS files for more details.

# Read in library functions
if [ "$(type -t patch_file_name)" != function ]
then
	if ! [ -r $CMDPATH/scripts/patchfns ]
	then
		echo "Cannot read library $CMDPATH/scripts/patchfns" >&2
		exit 1
	fi
	. $CMDPATH/scripts/patchfns
fi

usage()
{
	printf $"Usage: quilt refresh [-p n] [-f] [--no-timestamps] [--no-index] [--diffstat] [--sort] [--backup] [--strip-trailing-whitespace] [patch]\n"
	
	if [ x$1 = x-h ]
	then
		printf $"
Refreshes the specified patch, or the topmost patch by default.
Documentation that comes before the actual patch in the patch file is
retained.

It is possible to refresh patches that are not on top.  If any patches
on top of the patch to refresh modify the same files, the script aborts
by default.  Patches can still be refreshed with -f.  In that case this
script will print a warning for each shadowed file, changes by more
recent patches will be ignored, and only changes in files that have not
been modified by any more recent patches will end up in the specified
patch.

-p n	Create a -p n style patch (-p0 or -p1 supported).

-u, -U num, -c, -C num
	Create a unified diff (-u, -U) with num lines of context. Create
	a context diff (-c, -C) with num lines of context. The number of
	context lines defaults to 3.

--no-timestamps
	Do not include file timestamps in patch headers.
	
--no-index
	Do not output Index: lines.

--diffstat
	Add a diffstat section to the patch header, or replace the
	existing diffstat section.

-f	Enforce refreshing of a patch that is not on top.

--backup
	Create a backup copy of the old version of a patch as patch~.

--sort	Sort files by their name instead of preserving the original order.

--strip-trailing-whitespace
	Strip trailing whitespace at the end of lines.
"
		exit 0
	else
		exit 1
	fi
}

die ()
{
	local status=$1
	[ -n "$tmp_patch" ] && rm -f $tmp_patch
	[ -n "$tmp_header" ] && rm -f $tmp_header
	[ -n "$tmp_result" ] && rm -f $tmp_result
	exit $status
}

options=`getopt -o p:uU:cC:fh --long no-timestamps,diffstat,backup,sort \
			      --long no-index \
			      --long strip-trailing-whitespace -- "$@"`

if [ $? -ne 0 ]
then
	usage
fi

eval set -- "$options"

opt_format=-u
while true
do
	case "$1" in
	-p)
		opt_strip_level=$2
		shift 2 ;;
	-f)
		opt_force=1
		shift ;;
	-u|-c)
		opt_format=$1
		shift ;;
	-U|-C)
		opt_format="$1 $2"
		shift 2 ;;
	-h)
		usage -h ;;
	--no-timestamps)
		QUILT_NO_DIFF_TIMESTAMPS=1
		shift ;;
	--no-index)
		QUILT_NO_DIFF_INDEX=1
		shift ;;
	--diffstat)
		opt_diffstat=1
		shift ;;
	--backup)
		QUILT_BACKUP=1
		shift ;;
	--sort)
		opt_sort=1
		shift ;;
	--strip-trailing-whitespace)
		opt_strip_whitespace=1
		shift ;;
	--)
		shift
		break ;;
	esac
done

if [ $# -eq 1 ]
then
	opt_patch=$1
elif [ $# -gt 1 ]
then
	usage
fi

QUILT_DIFF_OPTS="$QUILT_DIFF_OPTS $opt_format"

if [ -n "$opt_patch" ]
then
	if ! patch=$(find_patch $opt_patch)
	then
		printf $"Patch %s is not in series\n" \
		       "$(print_patch $opt_patch)" >&2
		exit 1
	fi
	if ! is_applied "$patch"
	then
		printf $"Patch %s is not applied\n" \
		       "$(print_patch $patch)" >&2
		exit 1
	fi
else
	patch=$(top_patch)
	if [ -z "$patch" ]
	then
		printf $"No patches applied\n" >&2
		exit 1
	fi
fi

if [ -z "$opt_strip_level" ]
then
	opt_strip_level=$(patch_strip_level $patch)
fi
if [ $opt_strip_level -gt 1 ]
then
	printf $"Cannot refresh patches with -p%s, please specify -p0 or -p1 instead\n" "$opt_strip_level\n" >&2
	exit 1
fi

trap "die 1" SIGTERM

tmp_patch=$(gen_tempfile)

if [ -z "$opt_sort" ]
then
	files=( $(files_in_patch_ordered $patch) )
else
	files=( $(files_in_patch $patch | sort) )
fi

for file in "${files[@]}"
do
	old_file=$(backup_file_name $patch $file)
	next_patch=$(next_patch_for_file $patch $file)
	if [ -z "$next_patch" ]
	then
		new_file=$file
	else
		new_file=$(backup_file_name $next_patch $file)
		files_were_shadowed=1
	fi
	if ! diff_file $file $old_file $new_file >> $tmp_patch
	then
		printf $"Diff failed, aborting\n" >&2
		die 1
	fi

	if [ -n "$files_were_shadowed" -a -z "$opt_force" ]
	then
		printf $"More recent patches modify files in patch %s. Enforce refresh with -f.\n" "$(print_patch $patch)" >&2
		die 1
	fi

	if [ -n "$files_were_shadowed" -a -n "$opt_strip_whitespace" ]
	then
		printf $"Cannot use --strip-trailing-whitespace on a patch that has shadowed files.\n" >&2
	fi
done

if ! [ -s $tmp_patch ]
then
	printf $"Nothing in patch %s\n" "$(print_patch $patch)" >&2
	die 1
fi

# Check for trailing whitespace
if [ -z "$opt_strip_whitespace" ]
then
	$CMDPATH/scripts/remove-trailing-ws -n -p$opt_strip_level \
	< $tmp_patch
else
	tmp_patch2=$(gen_tempfile)
	if $CMDPATH/scripts/remove-trailing-ws -p$opt_strip_level \
					< $tmp_patch > $tmp_patch2
	then
		rm -f $tmp_patch
		tmp_patch=$tmp_patch2
	fi
fi
# FIXME: no stripping of non-topmost patch !!!

patch_file=$(patch_file_name $patch)

trap "" SIGINT

if ! tmp_header=$(gen_tempfile)
then
	die 1
fi

mkdir -p $(dirname $patch_file)

if ! cat_file $patch_file | patch_header > $tmp_header
then
	die 1
fi

tmp_result=$(gen_tempfile) || die 1

if [ -n "$opt_diffstat" ]
then
	diffstat="$(/usr/bin/diffstat -p$opt_strip_level $tmp_patch)" || die 1
	awk '
	    function print_diffstat(arr, i) {
	      split(diffstat, arr, "\n")
	      for (i=1; i in arr; i++)
		print prefix arr[i]
	    }
	    BEGIN	{ split(diffstat, ds_arr, /\n/) }
			{ prefix=""
			  if (index($0, "#") == 1)
			    prefix="#"
			}
	    /^#? .* \| /	{ eat = eat $0 "\n"
			  next }
	    /^#? .* files? changed(, .* insertions?\(\+\))?(, .* deletions?\(-\))?/ \
			{ print_diffstat()
			  diffstat = "" ; eat = ""
			  next }
			{ print eat $0
			  eat = "" }
	    END		{ printf "%s", eat
	    		  if (diffstat != "") {
			    print_diffstat()
			    print prefix
			  }
			}
	    ' diffstat="$diffstat" \
	    $tmp_header > $tmp_result
else
	cat $tmp_header > $tmp_result
fi

cat $tmp_patch >> $tmp_result

if [ -e $patch_file ] && \
   /usr/bin/diff -q $patch_file $tmp_result > /dev/null
then
	printf $"Patch %s is unchanged\n" "$(print_patch $patch)"
elif ( [ -z "$QUILT_BACKUP" -o ! -e $patch_file ] || \
       mv $patch_file $patch_file~ ) && \
     cat_to_new_file $patch_file < $tmp_result
then
	printf $"Refreshed patch %s\n" "$(print_patch $patch)"
else
	die 1
fi

touch $QUILT_PC/$patch/.timestamp

rm -f $QUILT_PC/$patch~refresh
if ! change_db_strip_level -p$opt_strip_level $patch
then
	die 1
fi
die 0
### Local Variables:
### mode: shell-script
### End:
# vim:filetype=sh
